package com.machine.filling.db.dao;

import android.provider.Settings;
import android.util.Log;

import com.machine.filling.MyApp;
import com.machine.filling.db.greendao.TempOrderModleDao;
import com.machine.filling.db.modle.CardTempModle;
import com.machine.filling.db.modle.GunInfoModle;
import com.machine.filling.db.modle.TempOrderModle;
import com.machine.filling.net.serialPort.receive.Receive_EndFueling;
import com.machine.filling.net.serialPort.receive.Receive_MachineState;
import com.machine.filling.net.ws.response.WsResCardInfoBean;
import com.machine.filling.util.Common;
import com.machine.filling.util.HexUtils;
import com.machine.filling.util.StringUtil;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

/**
 * Created by Administrator on 2018/3/29 0029.
 */

public class TempOrderDao {
    private static TempOrderDao instance;
    private static TempOrderModleDao tempOrderModleDao;
    private static TempOrderModle tempOrderModle;
    private final String deviceNum;

    private TempOrderDao() {
        deviceNum = Settings.System.getString(MyApp.getInstance().getContentResolver(), Settings.Secure.ANDROID_ID);

    }

    public static TempOrderDao getInstance() {
        if (instance == null) {
            instance = new TempOrderDao();
            tempOrderModleDao = MyApp.getInstance().getDaoSession().getTempOrderModleDao();
            tempOrderModle = new TempOrderModle();
        }
        return instance;
    }

    public void createTempModle(String portNum, WsResCardInfoBean cardInfoBean) {
        GunInfoModle gunInfoModle = GunInfoDao.getInstance().queryBytPortNum(portNum);
        tempOrderModle.setCustomName(cardInfoBean.getName());
        tempOrderModle.setOilCardType(cardInfoBean.getType());
        tempOrderModle.setOilCardNum(cardInfoBean.getCardNum());
        tempOrderModle.setOilTypeName(gunInfoModle.getTypeName());
        tempOrderModle.setOilTypeUnitPrice(gunInfoModle.getPrice() + "");
    }


    public TempOrderModle queryByPortNum(String portNum) {
        List<TempOrderModle> tempOrder = tempOrderModleDao.queryBuilder().where(TempOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (tempOrder != null && tempOrder.size() != 0) {
            return tempOrder.get(tempOrder.size() - 1);
        } else {
            return null;
        }
    }

    public void deleteAll() {
        tempOrderModleDao.deleteAll();
    }

    public void deleteByPortNum(String portNum) {
        TempOrderModle tempOrderModle = queryByPortNum(portNum);
        if (tempOrderModle != null) {
            tempOrderModleDao.delete(tempOrderModle);
        }
    }

    /**
     * 油卡加油创建新订单
     *
     * @return 订单编号
     */
    public String createNewOrder_1(String portNum, String orderNum, String orderType) {
//        deleteByPortNum(portNum);
        CardTempModle card = CardTempDao.getInstance().queryByPortNum(portNum);
        GunInfoModle gun = GunInfoDao.getInstance().queryBytPortNum(portNum);
        String orderNu = StringUtil.createOrderNum();
        tempOrderModle = new TempOrderModle();
        tempOrderModle.setPortNum(portNum);
        if (StringUtil.isNullOrEmpty(orderNum)) {
            tempOrderModle.setOrderNum(orderNu);//订单编号
        } else {
            orderNu = orderNum;
        }

        tempOrderModle.setOilCardType("1".equals(orderType) ? "" : card.getType());//油卡类型
        tempOrderModle.setOilCardNum("1".equals(orderType) ? "" : card.getCardNum());//油卡编号
        tempOrderModle.setOilTypeName(gun.getTypeName());//油品名称
        tempOrderModle.setOilTypeUnitPrice(gun.getPrice());//油品单价
        tempOrderModle.setCustomName(card.getName());//用户姓名
        tempOrderModle.setOrderType(orderType);//1预约 0未预约
        tempOrderModle.setPayState("1".equals(orderType) ? Common.ORDER_PAYED : Common.ORDER_UNPAY);//1未支付  2已支付未写卡  3已支付
        tempOrderModle.setFuelingTime(System.currentTimeMillis());//加油时间
        tempOrderModle.setUploadState(Common.ORDER_UPLOADSTATE_NO);//0 未上传 1已上传
        tempOrderModleDao.insert(tempOrderModle);
        return orderNu;
    }

    /**
     * 油卡加油过程中 更新加油订单数据
     *
     * @param portNum
     * @param cmd_state
     */
    public void updateFuelingData_2(String portNum, Receive_MachineState cmd_state) {
        // TODO: 2018/4/8 0008
        List<TempOrderModle> list = tempOrderModleDao.queryBuilder().where(TempOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        TempOrderModle tempOrder = list.get(list.size() - 1);
        tempOrder.setFuelVolume(cmd_state.getRealQuantity() + "");
        tempOrder.setFuelMoney(cmd_state.getRealAmount() + "");
        Log.d(TAG, "加油过程中: 加油体积" + cmd_state.getRealQuantity() + "加油金额:" + cmd_state.getRealAmount());
        tempOrderModleDao.update(tempOrder);
    }

    private static final String TAG = "TempOrderDao";

    /**
     * 油卡加油结束时  更新加油的数据
     */
    public void updateFueledData_3(String portNum, Receive_EndFueling cmd_end) {
        List<TempOrderModle> list = tempOrderModleDao.queryBuilder().where(TempOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        TempOrderModle tempOrder = list.get(list.size() - 1);
        tempOrder.setFuelVolume(cmd_end.getSheng() + "");

        //实付金额realMoney_9
        tempOrder.setPayTotalMoney(cmd_end.getRealMoney() + "");

        //应收金额() = 实付金额 + 优惠金额
        int fuelMoney = HexUtils.hex2Int(cmd_end.getReceivedMoney_4());
        String fuelMoneyD = HexUtils.formatDouble(fuelMoney*0.01,2);
        tempOrder.setFuelMoney(fuelMoneyD + "");

        //优惠金额 = 应收金额 - 实付金额
        double discountMoney = Double.parseDouble(fuelMoneyD) - cmd_end.getRealMoney();
        tempOrder.setDiscountMoney(HexUtils.formatDouble(discountMoney,2));

        //加油体积
        String volume = cmd_end.getSheng()+"";
        tempOrder.setFuelVolume(volume);

        //加油时间


        //凭证号
        tempOrder.setPingzhengCode(cmd_end.getErialNum_2());

        Log.d(TAG, "updateFueledData_3() returned: 加油结束: \n凭证号:" + cmd_end.getSheng()
                + "\n应收金额:" + fuelMoneyD + "\n实付金额:" + cmd_end.getRealMoney() + "\n优惠:" + HexUtils.formatDouble(discountMoney,2));
        tempOrderModleDao.update(tempOrder);
    }

    /**
     * 更新订单状态 支付成功
     *
     * @param portNum
//     * @param realPay
     */
    public void updateOrderStateSuccess(String portNum/*, double realPay*/) {
        List<TempOrderModle> list = tempOrderModleDao.queryBuilder().where(TempOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        TempOrderModle tempOrder = list.get(list.size() - 1);
        tempOrder.setUploadState(Common.ORDER_UPLOADSTATE_YES);
//        tempOrder.setPayTotalMoney(realPay + "");
        tempOrder.setIsError(false);
        tempOrderModleDao.update(tempOrder);
    }

    /**
     * 更新订单状态  支付失败
     *
     * @param portNum
     */
    public void updateOrderStateFailed(String portNum, String errorReason) {
        List<TempOrderModle> list = tempOrderModleDao.queryBuilder().where(TempOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        TempOrderModle tempOrder = list.get(list.size() - 1);
        tempOrder.setUploadState(Common.ORDER_UPLOADSTATE_NO);
        tempOrder.setIsError(true);
        tempOrder.setReason(errorReason);
        tempOrderModleDao.update(tempOrder);
    }

    /**
     * 查询降序
     * @param isOrdered 1预约 0未预约  2全部
     * @return
     */
//    public List<TempOrderModle> queryAllDesc(String isOrdered) {
//        return tempOrderModleDao.queryBuilder().orderDesc(TempOrderModleDao.Properties.FuelingTime).list();
//    }

    /**
     * 查询制定日期内数据
     *
     * @param date1     时间戳1
     * @param date2     时间戳2
     * @param isOrdered 0预约 1未预约 2全部
     * @return
     */
    public List<TempOrderModle> queryAllDesc(long date1, long date2, String isOrdered) {
        QueryBuilder queryBuilder = tempOrderModleDao.queryBuilder();
        //时间区间筛选
        queryBuilder = queryBuilder.where(TempOrderModleDao.Properties.FuelingTime.between(date1, date2));
        //订单状态筛选
        if (!"2".equals(isOrdered)) {
            queryBuilder = queryBuilder.where(TempOrderModleDao.Properties.OrderType.eq(isOrdered));
        }

        return queryBuilder.orderDesc(TempOrderModleDao.Properties.FuelingTime).list();
    }

    /**
     * 更新支付方式
     *
     * @param portNum
     * @param payMode
     */
    public void upadteOrderPayMode(String portNum, String payMode) {
        List<TempOrderModle> list = tempOrderModleDao.queryBuilder().where(TempOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        TempOrderModle tempOrder = list.get(list.size() - 1);
        tempOrder.setPayMode(payMode);
        tempOrderModleDao.update(tempOrder);
    }

    /**
     * 更新预约订单的 订单上传的状态
     *
     * @param portNum 串口号
     * @param uploadSuccess  (uploadState 是否上传  0 未上传 1已上传)
     */
    public void setOrderUploadState(String portNum, boolean uploadSuccess) {
        List<TempOrderModle> list = tempOrderModleDao.queryBuilder().where(TempOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        TempOrderModle tempOrder = list.get(list.size() - 1);
        if (uploadSuccess) {
            tempOrder.setUploadState("1");
        } else {
            tempOrder.setUploadState("0");
        }
        tempOrder.setPayMode(Common.PAY_MODE_ORDER);
        tempOrderModleDao.update(tempOrder);
    }

    /**
     * 更新订单的支付状态
     *
     * @param portNum
     * @param orderPayState 1未支付  2已支付未写卡  3已支付
     */
    public void updateOrderPayState(String portNum, String orderPayState) {
        List<TempOrderModle> list = tempOrderModleDao.queryBuilder().where(TempOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        TempOrderModle tempOrder = list.get(list.size() - 1);
        tempOrder.setPayState(orderPayState);
        tempOrderModleDao.update(tempOrder);
    }

    /**
     * 跟新订单号
     *
     * @param portNum
     * @param orderNum
     */
    public void upadteOrderNum(String portNum, String orderNum) {
        List<TempOrderModle> list = tempOrderModleDao.queryBuilder().where(TempOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        TempOrderModle tempOrder = list.get(list.size() - 1);
        tempOrder.setOrderNum(orderNum);
        tempOrderModleDao.update(tempOrder);
    }

//    public List<TempOrderModle> getUnUploadOrders(){
//        tempOrderModleDao.queryBuilder().where(TempOrderModleDao.Properties.)
//    }

}
